import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import { Input, Checkbox, Rate, Collapse, Modal, Upload, message, Popover } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import robotIcon from '@/assets/images/robot1.png';
import refreshIcon from '@/assets/images/refresh.png';
import readAloudIcon from '@/assets/images/readAloud.png';
import cannotReadIcon from '@/assets/images/canotRead.png';
import fileCloseIcon from '@/assets/images/fileClose.png';
import xleThumbnailIcon from '@/assets/images/xleThumbnail.png';
import enterIcon from '@/assets/images/enter.png';
import canNotEnterIcon from '@/assets/images/canNotEnter.png';
import stopIcon from '@/assets/images/stop.png';
import leftIcon from '@/assets/images/left-icon.png';
import recommendCloseIcon from '@/assets/images/recommendClose.png';
import vectorIcon from '@/assets/images/vector.png';
import skActiveIcon from '@/assets/images/sk-a.png';
import skIcon from '@/assets/images/sk.png';
import AssistantLeft from './assistant-left';
import SquareEnd from './file';
import language from "@/lang/zh";
import { marked } from "marked";
import axios from "axios";

import homeLogo from '@/assets/new_home/home-logo.png'
import notice from '@/assets/new_home/notice.png'
import addChart from "@/assets/new_home/add-chart.png"
import openIcon from "@/assets/new_home/open-icon.png"
import send from "@/assets/new_home/send.png"
import symbols from "@/assets/new_home/@.png"
import paper from "@/assets/new_home/paper.png"
import line from "@/assets/new_home/line.png"
import lineContainer from "@/assets/new_home/line-container.png"

import { sendChatMessage, getConversationMessages, createConversation, getQuizClassification, getQuizError, calculateFileRAG } from '@/config/api/home';

const { TextArea } = Input;
const { Panel } = Collapse;
const { Group: CheckboxGroup } = Checkbox;
const AssistantContainer = ({ bot_id = "app-J8oB2k4mNSwFGmOQalJQD8Oq", utils, showToast, pageName, bot_index }) => {
  localStorage.setItem("bot_id",bot_id)
  console.log('123123',bot_id)
  const [state, setState] = useState({
    isShowLikePopover: false,
    isYouKnown: false,
    questionType: 1,
    cancleLikeID: null,
    cancleLikeStatus: null,
    feedBackChecked: [],
    feedBackText: "",
    isShowVoiceInput: false,
    showFeedBack: false,
    feedBackSelect: [],
    inputFieldFocus: false,
    guessList: [],
    floatBottom: 0,
    activeNames: [""],
    activeNames1: ["1"],
    currentIndex: 0,
    sendText: "",
    classiFicationData: "",
    showArea: false,
    isPopverClose: true,
    isShowReco: false,
    isNewWindow: false,
    list: [],
    userInfo: null,
    eventSource: null,
    quizClassification: null,
    showConsultation: false,
    contentPadding: 0,
    consultationList: [],
    printEnd: true,
    printBackHtml: "",
    printAllHtml: "",
    isDisabled: false,
    isWait: false,
    messages: [],
    sendHidenText: "",
    userScrolled: false,
    answerObj: null,
    homeInfo: null,
    actionStop: false,
    feedBackScore: 0,
    checkedLang: false,
    weekdays: [],
    isReading: false,
    imgList: [],
    fileList: [],
    controller: null,
    modelType: false,
    isSk: false,
    printThinkAllHtml: "",
    printThinkBackHtml: "",
    fileLoading: false,
    currentTaskId: null, // Add this new state
    selectedAgent: null,
  });
  const currentIndexRef = useRef(0);
  const [questionType, setQuestionType] = useState(1);
  const [showFeedBack, setShowFeedBack] = useState(false);
  const [isDisabled, setIsDisabled] = useState(false);
  const [checkedLang, setCheckedLang] = useState(false);
  const [imgList, setImgList] = useState([]);
  const [fileList, setFileList] = useState([]);
  const [showPage, setshowPage] = useState("问答");
  const [isVisibleAssistantLeft, setIsVisibleAssistantLeft] = useState(true);
  const [isVisibleRecommend, setIsVisibleRecommend] = useState(true);
  const [isVisibleRecommendIcon, setIsVisibleRecommendIcon] = useState(false);
  const [isVisibleRecommendPopup, setIsVisibleRecommendPopup] = useState(false);
  const [conversation_id, setConversation_id] = useState(null);
  const [followUpContents, setFollowUpContents] = useState([]);
  const [isSearch, setIsSearch] = useState(false);
  const timeoutId = useRef(null);
  const isRoll = useRef(true)
  const [weekdays, setWeekdays] = useState(checkedLang
    ? ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    : ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]);

  const input = useRef(null);
  const scrollContainer = useRef(null);
  const assistantLeftRef = useRef(null);


  const cards = [
    { id: 1, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
    { id: 2, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
    { id: 3, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
    { id: 4, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
    { id: 5, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
    { id: 6, title: '面试意见符号', subtitle: '面试时的需注意事项是危险指标吗?' },
  ];



  useEffect(() => {
    setWeekdays(checkedLang
      ? ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
      : ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]);
  }, [checkedLang]);
  const handleKeyDown = (event) => {
    if (event.shiftKey && event.key === 'Enter') {
      event.preventDefault();
      setSendText(prevText => prevText + '\n');
    } else if (event.key === 'Enter') {
      event.preventDefault();
      sendQa();
    }
  };

  const getFileDetails = (item) => {
    return new Promise((resolve) => {
      if (item.resourceFile && item.fileId) {
        let urls = item.resourceFile.split(",");
        let ids = item.fileId.split(",");
        let docList = [];
        for (let i = 0; i < urls.length; i++) {
          const url = urls[i];
          axios(url, { method: "HEAD" })
            .then((response) => {
              const fileName = url.substring(url.lastIndexOf("/") + 1);
              docList.push({
                fileName: fileName.includes('_') ? fileName.substring(0, fileName.lastIndexOf('_')) : fileName,
                fileUrl: url,
                fileId: ids[i],
                fileType: fileName.split('.').pop().toLowerCase(),
              });
              if (docList.length === urls.length) {
                resolve(docList);
              }
            })
            .catch((error) => {
              console.error("Unable to get file information", error);
            });
        }
      }
    });
  };

  const containerStyle = {
    height: (imgList.length > 0 || (fileList.length > 0 && !isDisabled)) ? "53.9294vh" : "64.009vh",
  };

  const onRateChange = (value, item) => {
    setFeedBackScore(value);

    setConsultationList(prevData => {
      return prevData.map(i => {
        if (i.requestId === item.requestId) {
          return { ...i, isShowRateOpBox: true };
        }
        return i;
      });
    });
  };

  const handleClick = (event) => {
    const target = event.target;
    if (target.matches(".phone-tips")) {
      setConsultationList(prevList => {
        return prevList.map(item => {
          if (item.requestId && item.requestId === target.getAttribute("data-id")) {
            return { ...item, activeNames1: ["1"] };
          }
          return item;
        });
      });
    }
    if (target.matches(".doc-tips")) {
      const position = target.getAttribute("data-position");
      if (position) {
        scrollToPosition(position);
      }
    }
  };
  const readText = (text) => {
    if ("speechSynthesis" in window) {
      console.log("Browser supports speech synthesis");
    } else {
      alert("Browser does not support speech synthesis");
      return;
    }
    text = text.replace(/<.*?>/g, "");
    if (text) {
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.lang = checkedLang ? "en-US" : "zh-CN";
      utterance.pitch = 1;
      utterance.rate = 1;
      utterance.addEventListener("end", onReadEnd);
      speechSynthesis.speak(utterance);
      setIsReading(true);
    }
  };
  const onReadEnd = () => {
    setIsReading(false);
  };
  const stopReading = () => {
    if (speechSynthesis.speaking) {
      speechSynthesis.cancel();
      setIsReading(false);
    }
  };
  const toggleVisibility = useCallback((type) => {
    if (type === 1) { // 使用严格相等判断
      setIsVisibleRecommendIcon(prev => !prev);
      setIsVisibleRecommendPopup(prev => !prev);
    } else if (isVisibleRecommend) {
      setIsVisibleRecommend(false);
      setIsVisibleRecommendIcon(true);
    }
  }, [isVisibleRecommend]); // 添加依赖项

  const scrollToPosition = (position) => {
    let attr = position.split("%");
    let indexs = attr[1].replace(/\[|\]/g, "");
    const element = document.getElementsByClassName(`${attr[0]}`);

    setConsultationList(prevList => {
      const newList = [...prevList];

      for (let i = 0; i < newList.length; i++) {
        if (
          newList[i].questionType &&
          newList[i].questionType === 1 &&
          newList[i].requestId === attr[0]
        ) {
          newList[i].activeNames = ["1"];

          if (
            newList[i].answerRaw &&
            newList[i].answerRaw.docReferencesDistinct?.length > 0
          ) {
            newList[i].answerRaw.docReferencesDistinct.forEach((j) => {
              j.active = hasCommonCharacters(indexs, j.indexId.toString());
            });
          }
        } else if (newList[i].questionType && newList[i].questionType === 1) {
          newList[i].activeNames = [];

          if (
            newList[i].answerRaw &&
            newList[i].answerRaw.docReferencesDistinct?.length > 0
          ) {
            newList[i].answerRaw.docReferencesDistinct.forEach((j) => {
              j.active = false;
            });
          }
        }
      }

      return newList;
    });

    if (scrollContainer && scrollContainer.current) {
      scrollContainer.current.scrollTop =
        element[0].offsetTop + scrollContainer.current.scrollTop + 100
    }
  };

  const sendQa = () => {
    if (imgList.length > 0 || questionType === 6) {
      if (questionType !== 6) {
        setIsNewWindow(true);
        input.current.focus();
        setConsultationList([]);
        setGuessList([]);
        setSessionId("");
        setIsShowLikePopover(false);
        window.scrollTo(0, document.body.scrollHeight);
      }
      setQuestionType(6);
    }

    if (questionType !== 7 && questionType !== 8 && fileList.length > 0) {
      setIsNewWindow(true);
      input.current.focus();
      setConsultationList([]);
      setGuessList([]);
      setSessionId("");
      setIsShowLikePopover(false);
      window.scrollTo(0, document.body.scrollHeight);
      setQuestionType(7);
    } else if (questionType === 7 && fileList.length >= 0) {
      setFileList([]);
      setQuestionType(7);
    }

    initSSE();
    toggleVisibility(0);
  };
  const hasCommonCharacters = (str1, str2) => {
    const set2 = new Set(str2.split(","));
    for (let char of set2) {
      if (str1.includes(char)) {
        return true;
      }
    }
    return false;
  };

  const openFile = (e) => {
    if (e.filePath) {
      location.href = e.filePath;
    } else {
      alert("No source document path available");
    }
  };
  useEffect(() => {
    setshowPage(pageName);
    createSession(true);
  }, [bot_id, pageName]);

  const openNewWindow = (type = 1) => {
    if (type === 2) {
      if (pageName === "问答") {
        setshowPage("问答");
        createSession(true);
      }
    } else if (type === 3) {
      createSession(true);
    }

    setIsVisibleRecommend(true);
    setIsVisibleRecommendIcon(false);
    setIsVisibleRecommendPopup(false);
    setIsNewWindow(true);
    input.current?.focus();
    setConsultationList([]);
    setGuessList([]);
    setSessionId("");
    setQuestionType(type);
    setIsShowLikePopover(false);
    window.scrollTo(0, document.body.scrollHeight);
    stopReceiveData(2);
    alert(checkedLang ? language.messageEN.newTalk : language.messageZH.newTalk);
  };
  const changeLange = () => {
    setCheckedLang(prev => !prev);
    if (parentCheckedLang) {
      parentCheckedLang(!checkedLang);
    }
    getFeedBackSelect();
  };
  const bindRefresh = async (item) => {
    setSendHidenText(item.questionContent);

    if (questionType === 6 && item.resourceFile) {
      const uploadedFile = {
        imgUrl: item.resourceFile,
      };
      setImgList([uploadedFile]);
    }

    if (questionType === 7 && item.resourceFile) {
      const files = await getFileDetails(item);
      setFileList(files);
    }

    initSSE();
  };
  const stopReceiveData = useCallback(async (type) => {

    if (state.currentTaskId) {
      try {
        await fetch(`/api/chat-messages/${state.currentTaskId}/stop`, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' +bot_id,
            'Content-Type': 'application/json'
          },
          data:{ "user": "abc-123"}
        });
      } catch (error) {
        console.error('Error stopping message:', error);
      }
    }
    
    setState(prev => ({
      ...prev,
      isDisabled: false,
      printEnd: true,
      currentTaskId: null,
      actionStop: true
    }));
  }, [state.currentTaskId]);

  const getFooterHeight = useCallback(() => {
    setState(prev => ({ ...prev, inputFieldFocus: false }));
    setTimeout(() => {
      const footerHeight = document.querySelector(".assistant-footer")?.clientHeight;
      setState(prev => ({ ...prev, floatBottom: footerHeight }));
      return footerHeight || 54;
    }, 0);
  }, []);





  const scrollToBottom = useCallback(() => {
    if(!isRoll.current){
      return
    }

    if (scrollContainer && scrollContainer.current) {
      setTimeout(() => {
        // 获取当前内容总高度
        const contentHeight = scrollContainer.current.scrollHeight;
        // 获取可视区域高度
        const visibleHeight = scrollContainer.current.clientHeight;
        // 获取底部输入框高度
        const footerHeight = document.querySelector(".assistant-footer")?.clientHeight || 80;

        // 计算需要滚动的位置 - 确保最新消息完全可见
        const scrollPosition = contentHeight - visibleHeight + footerHeight;

        // 应用滚动
        scrollContainer.current.scrollTop = scrollPosition;
      }, 150); // 稍微增加延迟确保DOM完全更新
    }
  }, []);

  // 监听消息列表变化
  useEffect(() => {
    if (state.consultationList.length > 0) {
      // 当消息列表更新时自动滚动
      console.log("isRoll.current",isRoll.current)
      scrollToBottom();
    }
  }, [state.printEnd]);

  // 监听打字效果状态
  useEffect(() => {
    if (!state.printEnd) {
      const typingScrollInterval = setInterval(scrollToBottom, 300);
      return () => clearInterval(typingScrollInterval);
    }
  }, [state.printEnd, scrollToBottom]);

  const handleScroll = useCallback(() => {
    if (scrollContainer && scrollContainer.current) {
      if (
        scrollContainer.current.scrollTop + scrollContainer.current.clientHeight <
        scrollContainer.current.scrollHeight - 10
      ) {
        setState(prev => ({ ...prev, userScrolled: true }));
      } else {
        setState(prev => ({ ...prev, userScrolled: false }));
      }
    }
  }, []);



  const getMessages = useCallback(async () => {
    try {
      const res = await getConversationMessages({ "user": "abc-123", "conversation_id": localStorage.getItem("conversation_id"), "order": "ASC" });
      if (res && res.data) {
        return res;
      } else {
        console.error("Invalid response format:", res);
        return { data: [] };
      }
    } catch (error) {
      console.error("Error getting messages:", error);
      if (error.response) {
        console.error("Error response:", error.response.data);
      }
      return { data: [] };
    }
  }, [conversation_id]);

  const updateContent = useCallback((data) => {
    setIsDisabled(true);
    isRoll.current = true
    if (currentIndexRef.current < data.length) {
      let currentChar = data[currentIndexRef.current];
      if (currentChar !== undefined) {
        setState(prev => ({
          ...prev,
          printBackHtml: prev.printBackHtml + currentChar,
        }));

      }

      currentIndexRef.current += 1;
      timeoutId.current = setTimeout(() => {
        updateContent(data);
      }, 100); // 减少延迟时间，使打字效果更流畅
    } else {
      setIsDisabled(false);
      isRoll.current = false
      setState(prev => ({
        ...prev,
        sendHidenText: '',
        printEnd: false,
        isWait: false,
        isDisabled: false,
      }));

    }

  }, [state.currentIndex, state.printAllHtml, state.printBackHtml]);

  const pollForAnswer = useCallback(async (isUpdateContent = true) => {
    isRoll.current = true
    const res = await getMessages();
    if (res.data.length === 0) {
      return
    }
    const consultationList = res.data.flatMap((item, index) => {
      const questionResult = {
        text: item.query,
        type: 0,
        imgList: [],
        fileList: [],
        answerContent: item.answer,
        printEnd: false,
      };

      const answerResult = {
        text: item.query,
        type: 1,
        imgList: [],
        fileList: [],
        answerContent: item.answer,
        printEnd: true,
      };

      return [questionResult, answerResult];
    })



    setState(prevState => ({
      ...prevState,
      sendText: '',
      isWait: false,
      printEnd: false,
      isDisabled: false,
      printAllHtml: consultationList[consultationList.length - 1].answerContent,
      currentIndex: 0,
      consultationList: consultationList
    }));

    setIsVisibleRecommend(false);


    // 如果需要更新内容
    if (isUpdateContent && res.data.length > 1) {
      const data = {
        answerContent: consultationList[consultationList.length - 1].answerContent,
        questionContent: consultationList[consultationList.length - 1].text
      };

    } else {
      setState(prevState => ({
        ...prevState,
        printBackHtml: consultationList[consultationList.length - 1].answerContent
      }));
    }

  }, [getMessages, updateContent]);


  const createSession = useCallback(async (isCreate = true) => {
    if (localStorage.getItem('conversation_id') && !isCreate) {
      let conversation_id = JSON.parse(localStorage.getItem('conversation_id'));
      setConversation_id(conversation_id);
      await pollForAnswer(false);
    } else {
      setIsVisibleRecommend(true)
      localStorage.setItem("conversation_id", '')
      setState(prevState => ({
        ...prevState,
        isWait: false,
        printEnd: false,
        isDisabled: false,
        consultationList: []
      }));
    }
  }, [bot_id]);



  const sendMessage = useCallback(
   
    async (sendText) => {
      console.log("sendMessage",bot_id)
      try {
        currentIndexRef.current = 0;
        setState(prev => ({
          ...prev,
          printBackHtml: '',
          printAllHtml: '',
          imgList: []
        }));

        const headers = {
          Authorization: "Bearer "+bot_id,
          "Content-Type": "application/json",
        };

        const requestData = {
          "inputs": {},
          "query": sendText,
          "response_mode": "streaming",
          "conversation_id": localStorage.getItem("conversation_id"),
          "user": "abc-123",
          "files": [
            {
              "type": "image",
              "transfer_method": "remote_url",
              "url": state.imgList
            }
          ]
        };

        const controller = new AbortController();
        const response = await fetch('/api/chat-messages', {
          method: 'POST',
          headers: headers,
          body: JSON.stringify(requestData),
          signal: controller.signal
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let conversationId = null;
        let fullText = '';
        let taskId = null;

        setState(prev => ({
          ...prev,
          isWait: true,
          printEnd: true,
          imgList: []
        }));

        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n').filter(line => line.trim() !== '');
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.substring(6));
                if (data.answer || data.message) {
                  const newContent = data.answer || data.message || '';
                  fullText += newContent;
                  updateContent(fullText);
                }
                if (data.conversation_id && !conversationId) {
                  conversationId = data.conversation_id;
                  localStorage.setItem('conversation_id', conversationId);
                  setConversation_id(conversationId);
                }
                if (data.task_id && !taskId) {
                  taskId = data.task_id;
                  setState(prev => ({ ...prev, currentTaskId: taskId }));
                }
              } catch (e) {
                console.error('Error parsing SSE data:', e);
              }
            }
          }
        }

      } catch (error) {
        console.error("Error sending message:", error);
        if (error.response) {
          console.error("Error response:", error.response.data);
        }
        showToast("发送消息失败");
      }
    },
    [conversation_id]
  );



  const [isPanelOpen, setIsPanelOpen] = useState(false);
  const [selectedData, setSelectedData] = useState('');

  const togglePanel = () => {
    setIsPanelOpen(!isPanelOpen);
    setIsVisibleAssistantLeft(!isVisibleAssistantLeft);
  };

  const handleItemSelected = (item) => {
    setSelectedData(item);
    console.log('Selected Item:', item);
  };



  const clickItemQa = useCallback((e, type) => {
    if (state.questionType === 6 || state.questionType === 7) {
    }

    setState(prev => ({
      ...prev,
      isPopverClose: false,
      isYouKnown: type !== 3,
      questionType: type,
    }));

    window.scrollTo(0, document.body.scrollHeight);

    if (!state.isDisabled) {
      setState(prev => ({ ...prev, sendHidenText: e }));
      initSSE();
    }
  }, [state.questionType, state.isDisabled]);

  const initTextSSE = useCallback(async (sendText) => {
    setState(prev => ({ ...prev, printEnd: true }));
    isRoll.current = true
    await sendMessage(sendText);
    await pollForAnswer();
  }, [sendMessage, pollForAnswer]);

  const initFileSSE = useCallback((sendText) => {
    const eventSourceUrl = process.env.VUE_APP_BASE_API_URL +
      `/wechatApi/calAliFileRag?questionContent=${encodeURIComponent(
        sendText
      )}&questionType=${state.questionType}&lang=${state.checkedLang ? "en" : "zh"
      }&token=${localStorage.getItem("token")}&requestTime=${moment().valueOf()}${state.sessionId ? `&sessionId=${state.sessionId}` : ''
      }`;

    const controller = new AbortController();
    const { signal } = controller;

    setState(prev => ({ ...prev, controller }));

    let imgList = [];
    let fileIdLis = [];

    if (state.fileList.length > 0) {
      imgList = state.fileList.map(item => item.fileUrl);
      fileIdLis = state.fileList.map(item => item.fileId);
    }
    // try {
    //   fetchEventSource(eventSourceUrl, {
    //     method: "POST",
    //     signal: signal,
    //     headers: {
    //       "Content-Type": "application/json;charset=UTF-8",
    //     },
    //     body: JSON.stringify({
    //       questionContent: sendText,
    //       sessionId: state.sessionId || localStorage.getItem("sessionId"),
    //       imgUrl: imgList,
    //       fileIds: fileIdLis,
    //       questionType: 7,
    //     }),
    //     onmessage(event) {
    //       setState(prev => ({ ...prev, fileList: [] }));

    //       let data = JSON.parse(event.data);

    //       setState(prev => {
    //         const newState = { ...prev };

    //         if (prev.isWait) {
    //           newState.isWait = false;
    //         }

    //         if (prev.printEnd) {
    //           newState.printEnd = false;
    //         }

    //         if (!prev.sessionId) {
    //           newState.sessionId = data.sessionId;
    //         }

    //         newState.answerObj = { ...data };
    //         newState.printAllHtml = data.answerContent;

    //         return newState;
    //       });

    //       updateContent(data);
    //     },
    //     onclose() {
    //       stopStream(1);
    //     },
    //     onerror(error) {
    //       console.info(error);
    //       throw error;
    //     },
    //   });
    // } catch (error) {
    //   console.error("Error in fetchEventSource:", error);
    // }
  }, [state.questionType, state.checkedLang, state.sessionId, state.fileList, updateContent]);

  const initSSE = useCallback((sendMessage) => {
    if (!state.sendHidenText) {
      setState(prev => ({ ...prev, sendHidenText: prev.sendText }));
    }
    const sendText = state.sendText || state.sendHidenText || sendMessage
    if (!sendText) {
      showToast("发送内容不能为空");
      return false;
    }
    if (state.isWait || state.isDisabled) {
      return;
    }
    setState(prev => ({

      ...prev,
      isDisabled: true,
      isNewWindow: false,
      isShowReco: false,
      isWait: true,
      printBackHtml: "",
      guessList: [],
      showConsultation: true,
      consultationList: [...prev.consultationList,

      {
        text: sendText,
        type: 0,
        imgList: prev.imgList,
        fileList: prev.fileList
      }
      ],

      sendText: ""
    }));
    setIsVisibleRecommend(false)
    // 确保 scrollContainer 已经初始化
    if (scrollContainer && scrollContainer.current) {
      scrollToBottom();
    }

    if (state.questionType === 6) {
      // 处理图片类型消息
    } else if (state.questionType === 7) {
      initFileSSE(sendText);
    } else if (state.questionType === 8) {
      initTextSSE(sendText);
    } else {
      initTextSSE(sendText);
    }
  }, [state, showToast, scrollToBottom, initFileSSE, initTextSSE]);

  const streamEndOp = useCallback(() => {
    if (assistantLeftRef.current?.getTop3QaList) {
      assistantLeftRef.current.getTop3QaList();
    }
    const stopStream = useCallback((type, msg = '') => {
      clearTimeout(timeoutId.current);
      setState(prev => ({
        ...prev,
        printBackHtml: prev.printAllHtml,
        isDisabled: false,
        sendHidenText: '',
        sendText: ''
      }));

      if (state.eventSource) {
        state.eventSource.close();
        clearTimeout(timeoutHandle.current);
      }

      if (state.controller) {
        state.controller.abort();
      }

      if (state.eventSource || state.controller) {
        if (state.isWait) {
          setState(prev => ({
            ...prev,
            consultationList: [
              ...prev.consultationList,
              {
                type: type,
                questionType: prev.questionType,
                answerContent: msg || (prev.actionStop
                  ? (prev.checkedLang ? language.messageEN.cancel : language.messageZH.cancel)
                  : (prev.checkedLang ? language.messageEN.feedback : language.messageZH.feedback)
                ),
              }
            ],
            isDisabled: false,
            sendHidenText: "",
            sendText: ""
          }));

          // emit("checkedDisabled", false);
        } else {
          const obj = state.answerObj;

          if (obj) {
            let html = state.printAllHtml +
              `<p style="font-weight:700;font-size: 10px; margin: 4px 0;display: block; color: #333;">* ${state.checkedLang ? language.messageEN.confirmation : language.messageZH.confirmation
              }</p>`;

            html = utils?.phoneReg(html, obj.requestId) || html;

            const updatedObj = {
              ...obj,
              answerContent: marked(html),
              answerRaw: obj.answerRaw && typeof obj.answerRaw !== 'string'
                ? JSON.parse(obj.answerRaw)
                : null,
              printEnd: true,
              activeNames: [],
              activeNames1: ["1"],
              ratevalue: 0,
              isShowRate: true,
              isShowRateOpBox: false
            };

            if (state.questionType !== 8) {
              if (obj.status === 1) {
                setState(prev => ({
                  ...prev,
                  consultationList: [...prev.consultationList, updatedObj]
                }));

                if (state.questionType !== 6 && state.questionType !== 7) {
                  getClassification(
                    state.sendText,
                    obj.requestId,
                    obj.sessionType || 0
                  );
                } else {
                  streamEndOp();
                }
              } else if (obj.status === 0) {
                if (state.questionType !== 6 && state.questionType !== 7) {
                  setState(prev => ({ ...prev, isWait: true }));
                  getClassification(
                    state.sendText,
                    obj.requestId,
                    obj.sessionType || 0,
                    updatedObj
                  );
                } else {
                  streamEndOp();
                }
              }

              if (
                state.isYouKnown &&
                obj.status === 1 &&
                obj.answerRaw?.docReferencesDistinct?.length > 0
              ) {
                getQuizYouAsk(state.sendText, obj.requestId, obj.sessionType || 0);
              }
            } else {
              setState(prev => ({
                ...prev,
                consultationList: [...prev.consultationList, updatedObj],
                isShowLikePopover: prev.consultationList.length === 2,
                isDisabled: false,
                sendHidenText: "",
                isWait: true,
                classiFicationData: null
              }));

              setTimeout(() => {
                let ele = document.querySelectorAll(".itema");
                ele[ele.length - 1].scrollIntoView({
                  behavior: "smooth",
                  block: "start",
                });
              }, 500);
            }
          }
        }

        setState(prev => ({
          ...prev,
          sendText: "",
          isWait: prev.answerObj && prev.answerObj.status === 0 ? true : false,
          printEnd: true,
          isYouKnown: false,
          printBackHtml: "",
          printAllHtml: "",
          printThinkAllHtml: "",
          printThinkBackHtml: "",
          currentIndex: 0,
          answerObj: null,
          actionStop: false,
          imgList: [],
          consultationList: type === 2 ? [] : prev.consultationList
        }));
      }
    }, [state, utils, streamEndOp, getClassification, getQuizYouAsk]);


    setState(prev => ({
      ...prev,
      isShowLikePopover: prev.consultationList.length === 2,
      isDisabled: false,
      sendHidenText: "",
      isWait: false,
      classiFicationData: null
    }));

    setTimeout(() => {
      let ele = document.querySelectorAll(".itema");
      ele[ele.length - 1]?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }, 500);
  }, []);
  const stopStream1 = useCallback((type, obj = null) => {
    if (state.quizClassification) {
      state.quizClassification.close();
    }

    let consultationList = [...state.consultationList];

    if (obj) {
      consultationList.push(obj);
    }

    for (let i = 0; i < consultationList.length; i++) {
      let classification = [];
      let arr = state.classiFicationData?.classContent?.split("|") || [];

      for (let j = 0; j < arr.length; j++) {
        arr[j] = arr[j].replace(
          /\ball\b/g,
          state.checkedLang
            ? language.messageEN.contacts
            : language.messageZH.contacts
        );

        if (obj && obj.status === 0 && arr[j].includes("业务领域")) {
          let typeText = arr[j].split(":")[1];
          obj.answerContent = obj.answerContent.replace(
            /<<类型>>|&lt;&lt;类型&gt;&gt;/g,
            `<span class="phone-tips" data-id=${obj.requestId} style="color: #5CB2FF">${typeText.trim()}</span>`
          );
        }

        arr[j] = utils?.phoneReg(arr[j], arr[j].requestId);
        let seconed = marked(arr[j]);
        arr[j] = seconed;
      }

      classification = arr;

      if (consultationList[i].requestId === state.classiFicationData?.requestId) {
        consultationList[i].classification = classification;
      }
    }

    setState(prev => ({
      ...prev,
      isShowLikePopover: consultationList.length === 2,
      isDisabled: false,
      sendHidenText: "",
      isWait: false,
      classiFicationData: null,
      consultationList
    }));

    // emit("checkedDisabled", false);

    setTimeout(() => {
      let ele = document.querySelectorAll(".itema");
      ele[ele.length - 1]?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }, 500);
  }, [state, utils]);

  const getClassification = useCallback((questionContent, requestId, sessionType, obj = null) => {
    let eventSourceUrl =
      process.env.VUE_APP_BASE_API_URL +
      `/wechatApi/quizCla?questionContent=${encodeURIComponent(
        questionContent
      )}&sessionId=${state.sessionId
      }&requestId=${requestId}&sessionType=${sessionType}&lang=${state.checkedLang ? "en" : "zh"
      }&token=` +
      localStorage.getItem("token");

    const quizClassification = new EventSource(eventSourceUrl);

    setState(prev => ({ ...prev, quizClassification }));

    quizClassification.onopen = () => { };

    quizClassification.onmessage = (event) => {
      setState(prev => ({
        ...prev,
        classiFicationData: JSON.parse(event.data)
      }));
    };

    quizClassification.onerror = (error) => {
      stopStream1(1, obj);
    };

    if (assistantLeftRef.current?.getTop3QaList) {
      assistantLeftRef.current.getTop3QaList();
    }
  }, [state.sessionId, state.checkedLang, stopStream1]);


  const getQuizYouAsk = useCallback((questionContent, requestId, sessionType) => {
    getQuizError({
      questionContent,
      requestId,
      sessionType,
      sessionId: state.sessionId,
      token: localStorage.getItem("token"),
    })
      .then((res) => {
        if (res.code === 200 && res.data.length > 0) {
          setState(prev => ({
            ...prev,
            guessList: res.data.map(i => i)
          }));

          setTimeout(() => {
            let ele = document.querySelectorAll(".itema");
            ele[ele.length - 1]?.scrollIntoView({
              behavior: "smooth",
              block: "start",
            });
          }, 500);
        }
      })
      .catch(error => {
        console.error("Error in getQuizYouAsk:", error);
      });
  }, [state.sessionId]);


  const [selectedLang, setSelectedLang] = useState('zh'); // 默认选中中文

  const changeLanguage = (lang) => {
    setSelectedLang(lang);
  };



  const getQuestionList = useCallback(() => {
    setIsSearch(
      state.checkedLang
        ? language.messageEN.bot_question[bot_index].isClick
        : language.messageZH.bot_question[bot_index].isClick
    );

    return state.checkedLang
      ? language.messageEN.bot_question[bot_index].question
      : language.messageZH.bot_question[bot_index].question;
  }, [state.checkedLang]);

  const seachQuestion = useCallback((value) => {
    setState(prev => ({ ...prev, sendText: value }));
    // sendQa(); - This function wasn't in the original code excerpt
  }, []);

  const updateThinkContent = useCallback((data) => {
    if (state.currentIndex < state.printThinkAllHtml.length) {
      setState(prev => ({
        ...prev,
        printThinkBackHtml: prev.printThinkBackHtml + prev.printThinkAllHtml[prev.currentIndex],
        currentIndex: prev.currentIndex + 1
      }));

      setTimeout(() => {
        updateThinkContent(data);
      }, 50);
    }
  }, [state.currentIndex, state.printThinkAllHtml]);


  // Computed properties equivalent
  const backHtm = useMemo(() => {
    return marked(state.printBackHtml);
  }, [state.printBackHtml]);

  const backThinkHtm = useMemo(() => {
    return marked(state.printThinkBackHtml || "");
  }, [state.printThinkBackHtml]);

  const handleImageUpload = (info) => {
    if (info.file.status === 'uploading') {
      setState(prev => ({ ...prev, fileLoading: true }));
      return;
    }
    if (info.file.status === 'done') {
      setState(prev => ({ 
        ...prev, 
        fileLoading: false,
        imgList: [{
          imgUrl: info.file.response.url,
          imgName: info.file.name,
          imgType: info.file.type,
          imgSize: formatFileSize(info.file.size)
        }]
      }));
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      setState(prev => ({ ...prev, fileLoading: false }));
      message.error(`${info.file.name} 上传失败`);
    }
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const uploadProps = {
    name: 'file',
    action: '/api/files/upload',
    headers: {
      authorization: 'Bearer '+ bot_id,
    },
    showUploadList: false,
    maxCount: 1,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    onChange: handleImageUpload,
  };

  const handleRemoveImage = () => {
    setState(prev => ({ ...prev, imgList: [] }));
  };

  // 模拟智能体列表数据
  const agentList = [
    { name: "问答智能体", id: 1 },
    { name: "文档智能体", id: 2 },
    { name: "知识库智能体", id: 3 }
  ];

  const handleAgentSelect = (agent) => {
    setState(prev => ({
      ...prev,
      selectedAgent: agent
    }));
  };

  const agentContent = (
    <div style={{ padding: '8px 0' }}>
      {agentList.map(agent => (
        <div
          key={agent.id}
          style={{
            padding: '8px 16px',
            cursor: 'pointer',
            backgroundColor: state.selectedAgent?.id === agent.id ? 'rgba(92, 178, 255, 0.1)' : 'transparent',
            transition: 'background-color 0.3s ease',
            ':hover': {
              backgroundColor: 'rgba(92, 178, 255, 0.1)'
            }
          }}
          onClick={() => handleAgentSelect(agent)}
        >
          {agent.name}
        </div>
      ))}
    </div>
  );

  return (
    <div className="assistant-container">
      {showPage === '问答' && (
        <div className="assistant-right">
          <div className="right-head">
            <div className='new-chart' onClick={() => createSession(true)}>
              <img src={addChart} alt="新建聊天" />
              新建聊天
            </div>
            {/* <div
              className="changeLange"
              style={{ opacity: state.questionType !== 8 ? '1' : '0' }}
            >
              {!state.checkedLang ? (
                <div
                  className="ZN"
                  onClick={() => state.questionType !== 8 ? changeLange() : ''}
                >
                  <div>
                    <span>中文</span>
                  </div>
                  <div>
                    <span>English</span>
                  </div>
                </div>
              ) : (
                <div className="EN" onClick={changeLange}>
                  <div>
                    <span>中文</span>
                  </div>
                  <div>
                    <span>English</span>
                  </div>
                </div>
              )}
            </div> */}
            <div className="changeLange">
              <div
                className={`language-option ${selectedLang === 'zh' ? 'active-lang' : ''}`}
                onClick={() => changeLanguage('zh')}
              >
                中文
              </div>
              <span className="separator active-lang">|</span>
              <div
                className={`language-option ${selectedLang === 'en' ? 'active-lang' : ''}`}
                onClick={() => changeLanguage('en')}
              >
                English
              </div>
              <div>


              </div>
            </div>

            <img src={openIcon} onClick={togglePanel} className={`cursor-pointer ${isPanelOpen ? 'active' : ''}`}></img>

            {((isVisibleAssistantLeft || isVisibleRecommendPopup) &&
              !(!isVisibleAssistantLeft && isVisibleRecommendPopup) &&
              !(isVisibleAssistantLeft && isVisibleRecommendPopup)) && (
                <div className="layout-1"></div>
              )}
            {(!isVisibleAssistantLeft && isVisibleRecommendPopup) && (
              <div className="layout-2"></div>
            )}
          </div>




          <div className={`content ${state.showConsultation ? 'consultation-mode' : ''}`}>
            <div
              className="consultation-container"
              style={containerStyle}
              onScroll={handleScroll}
            >
              {isVisibleRecommend && (
                <div className="greet">
                  {state.questionType !== 8 && state.consultationList.length === 0 && (

                    <div className="ai-icon">
                      <div><img src={homeLogo} />
                      </div>

                      {/* <div className="logo">
                        <img src={robotIcon} alt="小助手" width="48px" height="48px" />
                      </div>
                      <div className="con">
                        <span>
                          {state.checkedLang
                            ? language.messageEN.welcomeTop
                            : language.messageZH.welcomeTop},
                          {state.checkedLang
                            ? language.messageEN.welcomeBtm + language.messageEN.botTitle[bot_index]
                            : language.messageZH.welcomeBtm + language.messageZH.botTitle[bot_index]}
                        </span>
                        <div
                          className="con-text"
                          dangerouslySetInnerHTML={{
                            __html: state.checkedLang
                              ? language.messageEN.botDesc[bot_index]
                              : language.messageZH.botDesc[bot_index]
                          }}
                        ></div>
                      </div> */}
                    </div>

                  )}
                  <div className="home-card">
                    {cards.map((card) => (
                      <div
                        key={card.id}
                        className="card-item"
                        onClick={() => initSSE(card.subtitle)}
                      >
                        <div className="card-title-container">
                          <div className="notice-icon" ><img src={notice}></img></div>
                          <div className="card-title">{card.title}</div>
                        </div>
                        <p className="card-desc">{card.subtitle}</p>
                      </div>
                    ))}
                  </div>


                </div>
              )}


              {!isVisibleRecommend && (
                <div className="session-box" ref={scrollContainer}>
                  {state.consultationList.map((item, index) => (
                    <React.Fragment key={index}>
                      {item.type === 0 && (
                        <div className="item itema">
                          <div className="con">
                            <div
                              className="con-text fs-16"
                              dangerouslySetInnerHTML={{ __html: item.text }}
                            ></div>
                          </div>
                          {item.imgList && item.imgList.length > 0 && item.imgList[0].imgUrl && (
                            <div className="img-qa">
                              {item.imgList.map((i, idx) => (
                                <img key={idx} src={i.imgUrl} alt="" />
                              ))}
                            </div>
                          )}
                          {item.imgList && item.imgList.length > 0 && !item.imgList[0].imgUrl && (
                            <div className="img-qa">
                              {item.imgList.map((i, idx) => (
                                <img key={idx} src={i} alt="" />
                              ))}
                            </div>
                          )}
                          {item.fileList && item.fileList.length > 0 && (
                            <div className="file-qa">
                              <div className="uploadImg">
                                {item.fileList.map((i, idx) => (
                                  <div className="img" key={idx}>
                                    <img className="img-thumbnail" src={xleThumbnailIcon} alt="" />
                                    <span className="img-info">
                                      <div className="img-name">{i.fileName}</div>
                                      <div className="img-size">
                                        <div>{i.fileType}</div>
                                        <div>{i.fileSize}</div>
                                      </div>
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </div>
                      )}

                      {item.type === 2 && (
                        <div className="item itema">
                          <div className="con">
                            <div className="con-text fs-16">
                              <div className="voice-loader">
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                                <span></span>
                              </div>
                            </div>
                          </div>
                        </div>
                      )}

                      {(item.type === 1 || item.type === 6 || item.questionType) && (
                        <div className="item itemb">
                          {index !== state.consultationList.length - 1 && (
                            <div className="ai-icon">
                              {item.questionType !== 8 && (
                                <>
                                  <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                                  <span>
                                    {state.checkedLang
                                      ? language.messageEN.appTitle
                                      : language.messageZH.appTitle}
                                  </span>
                                </>
                              )}
                            </div>
                          )}

                          {index !== state.consultationList.length - 1 && (
                            <div className="con">
                              <div
                                className="con-text fs-16"
                                dangerouslySetInnerHTML={{ __html: item.answerContent }}
                                onClick={handleClick}
                              ></div>

                              <div className="features">
                                {!item.isError && !state.isDisabled && item.requestId && (
                                  <div className="con-opt">
                                    <div className="left">
                                      <img
                                        src={refreshIcon}
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          bindRefresh(item);
                                        }}
                                        alt=""
                                      />
                                      {!state.isReading && (
                                        <img
                                          src={readAloudIcon}
                                          onClick={() => readText(item.answerContent, item.isReading)}
                                          alt=""
                                        />
                                      )}
                                      {state.isReading && (
                                        <img
                                          src={cannotReadIcon}
                                          onClick={stopReading}
                                          alt=""
                                        />
                                      )}
                                    </div>
                                  </div>
                                )}

                                {item.isShowRate && (!item.isError && !state.isDisabled && item.requestId) && (
                                  <div className="rate">
                                    <div>
                                      {state.checkedLang
                                        ? language.messageEN.evaluation
                                        : language.messageZH.evaluation}
                                    </div>
                                    <div className="demo-rate-block">
                                      <Rate
                                        size="large"
                                        disabled={item.feedBackType == 99}
                                        value={item.feedBackScore}
                                        color={colors}
                                        onChange={(value) => onRateChange(value, item)}
                                      />
                                    </div>

                                    {!item.isShowRateOpBox && item.feedBackType !== 99 && (
                                      <div className="rate-submit">
                                        <div>
                                          {state.checkedLang
                                            ? language.messageEN.cancelAction
                                            : language.messageZH.cancelAction}
                                        </div>
                                        <div>
                                          {state.checkedLang
                                            ? language.messageEN.confirm
                                            : language.messageZH.confirm}
                                        </div>
                                      </div>
                                    )}

                                    {item.isShowRateOpBox && item.feedBackType !== 99 && (
                                      <div className="rate-submit active">
                                        <div
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            let data = [...state.consultationList];
                                            data.forEach((i, cindex) => {
                                              if (i.requestId === item.requestId) {
                                                i.feedBackType = state.cancleLikeStatus;
                                                i.ratevalue = 0;
                                                i.isShowRateOpBox = false;
                                                i.feedBackScore = 0;
                                                if (cindex === data.length - 1) {
                                                  setState(prev => ({
                                                    ...prev,
                                                    isShowLikePopover: false,
                                                    consultationList: data
                                                  }));
                                                }
                                              }
                                            });
                                          }}
                                        >
                                          {state.checkedLang
                                            ? language.messageEN.cancelAction
                                            : language.messageZH.cancelAction}
                                        </div>
                                        <div
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            showFeedBack(
                                              item.requestId,
                                              item.feedBackType == 2 ? 0 : 2,
                                              item.feedBackType,
                                              state.feedBackScore
                                            );
                                          }}
                                        >
                                          {state.checkedLang
                                            ? language.messageEN.confirm
                                            : language.messageZH.confirm}
                                        </div>
                                      </div>
                                    )}
                                  </div>
                                )}
                              </div>

                              {state.printEnd &&
                                item.answerRaw &&
                                item.answerRaw.docReferencesDistinct &&
                                item.answerRaw.docReferencesDistinct.length > 0 && (
                                  <div className={`con-file ${item.requestId}`}>
                                    <Collapse activeKey={item.activeNames}>
                                      <Panel
                                        key="1"
                                        header={state.checkedLang
                                          ? language.messageEN.reference
                                          : language.messageZH.reference}
                                        className="activeName"
                                      >
                                        {item.answerRaw.docReferencesDistinct.map((citem, cindex) => (
                                          <div
                                            key={cindex}
                                            className={`file-item fs-14 ${citem.active ? 'active' : ''}`}
                                            onClick={() => openFile(citem)}
                                          >
                                            <span className="iconfont icon-lianjie fs-24"></span>
                                            {citem.docName || ""}
                                            {citem.indexId && citem.indexId.length > 0 && (
                                              citem.indexId.map(ditem => (
                                                <span key={ditem}>[{ditem}]</span>
                                              ))
                                            )}
                                          </div>
                                        ))}
                                      </Panel>
                                    </Collapse>
                                  </div>
                                )}

                              {state.printEnd &&
                                item.classification &&
                                item.classification.length > 0 && (
                                  <div className="con-file">
                                    <Collapse activeKey={item.activeNames1}>
                                      <Panel
                                        key="1"
                                        header={state.checkedLang
                                          ? language.messageEN.business
                                          : language.messageZH.business}
                                        className="activeName"
                                      >
                                        {item.classification.map((citem, cindex) => (
                                          <div
                                            key={cindex}
                                            className="file-item fs-4"
                                            dangerouslySetInnerHTML={{ __html: citem }}
                                          ></div>
                                        ))}
                                      </Panel>
                                    </Collapse>
                                  </div>
                                )}
                            </div>
                          )}
                        </div>
                      )}
                    </React.Fragment>
                  ))}

                  {state.guessList.length > 0 && state.printEnd && !state.isDisabled && (
                    <div className="guess-to-ask">
                      <span>
                        {state.checkedLang
                          ? language.messageEN.iswant
                          : language.messageZH.iswant}
                      </span>
                      <div className="ask-list">
                        {state.guessList.map((item, index) => (
                          <div
                            key={index}
                            className="list-text"
                            onClick={() => clickItemQa(item, 3)}
                          >
                            <div>{item}</div>
                            <img src={vectorIcon} alt="" />
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {!state.printEnd && (
                    <div className="item itemb print">
                      <div className="ai-icon">
                        {state.questionType !== 8 && (
                          <>
                            <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                            <span>
                              {state.checkedLang
                                ? language.messageEN.appTitle
                                : language.messageZH.appTitle}
                            </span>
                          </>
                        )}
                      </div>
                      <div className="con">
                        <div className="con-text">
                          {!state.printBackHtml && (
                            <div
                              className="think-style"
                              dangerouslySetInnerHTML={{ __html: state.printAllHtml }}
                            ></div>
                          )}

                        </div>
                        <div
                          className="con-text fs-16"
                          dangerouslySetInnerHTML={{ __html: state.printBackHtml }}
                        ></div>
                      </div>
                    </div>
                  )}

                  <div className="tuijian" v-if="!state.isDisabled">
                    {followUpContents.map((item, index) => (
                      <div
                        key={index}
                        onClick={() => seachQuestion(item)}
                      >
                        <span className="recommend-one">{item}</span>
                      </div>
                    ))}
                  </div>

                  {state.isWait && (
                    <div className="item itemb">
                      <div className="ai-icon">
                        {state.questionType !== 8 && (
                          <>
                            <img className="avatar" src={robotIcon} width="48px" height="48px" alt="" />
                            <span>
                              {state.checkedLang
                                ? language.messageEN.appTitle
                                : language.messageZH.appTitle}
                            </span>
                          </>
                        )}
                      </div>
                      <div className="con loading-mask">
                        {/* <div className="load-15">
                          <div className="k-loader k-circle"></div>
                        </div> */}
                        <div className="ball"></div>
                        <div className="ball"></div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
          <div className="assistant-footer" onClick={(e) => e.stopPropagation()}>
            {state.imgList && state.imgList.length > 0 && !state.isDisabled && (
              <div className="img-preview">
                <div className="uploadImg">
                  {state.imgList.map((item, index) => (
                    <div className="img" key={index}>
                      <img className="img-thumbnail" src={item.imgUrl} alt="" />
                      <span className="img-info">
                        <div className="img-name">{item.imgName}</div>
                        <div className="img-size">
                          <div>{item.imgType}</div>
                          <div>{item.imgSize}</div>
                        </div>
                      </span>
                      <div className="closeImg">
                        <img
                          src={fileCloseIcon}
                          onClick={handleRemoveImage}
                          alt=""
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {state.fileList && state.fileList.length > 0 && !state.isDisabled && (
              <div className="img-preview">
                <div className="uploadImg">
                  {state.fileList.map((item, index) => (
                    <div className="img" key={index}>
                      <img className="img-thumbnail" src={xleThumbnailIcon} alt="" />
                      <span className="img-info">
                        <div className="img-name">{item.fileName}</div>
                        <div className="img-size">
                          <div>{item.fileType}</div>
                          <div>{item.fileSize}</div>
                        </div>
                      </span>
                      <div className="closeImg">
                        <img
                          src={fileCloseIcon}
                          onClick={() => {
                            const newFileList = [...state.fileList];
                            newFileList.splice(index, 1);
                            setState(prev => ({ ...prev, fileList: newFileList }));
                          }}
                          alt=""
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            <div className="option-area">
              <div onClick={(e) => {
                e.stopPropagation();
                setState(prev => ({ ...prev, showArea: !prev.showArea }));
              }}>
              </div>

              <div className="input-box">
                <div>
                  {!state.isShowVoiceInput && (
                    <TextArea
                      id="textarea-box"
                      value={state.sendText}
                      placeholder={state.checkedLang
                        ? language.messageEN.placeholderArr[bot_index]
                        : language.messageZH.placeholderArr[bot_index]}
                      rows={state.inputFieldFocus ? 4 : 1}
                      autoSize={{ maxRows: 3 }}
                      disabled={state.isDisabled}
                      onBlur={getFooterHeight}
                      onFocus={() => setState(prev => ({ ...prev, inputFieldFocus: true }))}
                      onKeyDown={handleKeyDown}
                      className={!state.inputFieldFocus ? 'textareaellipsis' : ''}
                      resize="none"
                      onChange={(e) => setState(prev => ({ ...prev, sendText: e.target.value }))}
                    />
                  )}
                </div>
                <div style={{ display: 'flex', justifyContent: "space-between" }} className='cursor-pointer'>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <img src={lineContainer} alt="Line Container" style={{ marginRight: '10px' }} />
                    <div style={{ position: 'relative', left: '-120px', color: 'gray' }}>
                      <Upload {...uploadProps}>
                        <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                          <img src={paper} alt="Symbols" style={{ marginRight: '5px' }} />
                          <span>添加内容</span>
                        </div>
                      </Upload>
                    </div>
                  </div>
                  <div className='send-container'>
                    {state.selectedAgent ? (
                      <Popover
                        content={agentContent}
                        title="选择智能体"
                        trigger="hover"
                        placement="top"
                      >
                        <span 
                          style={{ 
                            color: '#5CB2FF', 
                            marginRight: '10px',
                            cursor: 'pointer'
                          }}
                        >
                          @{state.selectedAgent.name}
                        </span>
                      </Popover>
                    ) : (
                      <Popover
                        content={agentContent}
                        title="选择智能体"
                        trigger="hover"
                        placement="top"
                      >
                        <img src={symbols} alt="Select Agent" style={{ cursor: 'pointer' }} />
                      </Popover>
                    )}
                    <img src={line} />
                    {!state.fileLoading && (state.sendText || state.sendHidenText || state.imgList.length > 0) ? (
                      <span>
                        {state.isDisabled && (
                          <img
                            src={stopIcon}
                            onClick={() => stopReceiveData(3)}
                            alt=""
                          />
                        )}
                        {!state.isDisabled && (
                          <img
                            src={send}
                            onClick={sendQa}
                            alt=""
                          />
                        )}
                      </span>
                    ) : (
                      <span>
                        {!state.isDisabled && (
                          <img src={send} alt="" />
                        )}
                      </span>
                    )}
                  </div>
                </div>
              </div>



              {/* {isVisibleRecommendIcon && state.questionType !== 8 && (
                <div className="recommendIcon">
                  <span onClick={() => toggleVisibility(1)}>
                    {state.checkedLang
                      ? language.messageEN.discover
                      : language.messageZH.discover}
                  </span>
                </div>
              )} */}
            </div>

            {state.questionType === 8 && (
              <div className="assistant-footer-box">
                <div
                  className={`sen ${state.isSk ? 'sen-active' : ''}`}
                  onClick={() => {
                    setState(prev => ({ ...prev, isSk: !prev.isSk }));
                  }}
                >
                  <img
                    src={state.isSk ? skActiveIcon : skIcon}
                    style={{ width: '20px' }}
                    alt=""
                  />
                  深度思考
                </div>
              </div>
            )}
          </div>



          <Modal
            open={state.showFeedBack}
            title=""
            width="40%"
            style={{ padding: '12px' }}
            footer={null}
            onCancel={() => setState(prev => ({ ...prev, showFeedBack: false }))}
          >
            <div className="feedback-box">
              <div className="title">
                <div className="title-left">
                  {state.checkedLang
                    ? language.messageEN.feed
                    : language.messageZH.feed}
                </div>
              </div>
              <div className="feedback-content">
                <CheckboxGroup
                  value={state.feedBackChecked}
                  onChange={(values) => setState(prev => ({ ...prev, feedBackChecked: values }))}
                >
                  {state.feedBackSelect.map(i => (
                    <Checkbox key={i.dictCode} value={i.dictLabel}>
                      {i.dictLabel}
                    </Checkbox>
                  ))}
                </CheckboxGroup>
                <TextArea
                  value={state.feedBackText}
                  onChange={(e) => setState(prev => ({ ...prev, feedBackText: e.target.value }))}
                  className="feedback-textarea"
                  placeholder={state.checkedLang
                    ? language.messageEN.feedContent
                    : language.messageZH.feedContent}
                  rows={8}
                />
              </div>
            </div>
          </Modal>


        </div>
      )}

      {showPage === "文档库" && (
        <div style={{ width: '95%', height: '100vh', overflow: 'auto' }}>
          <SquareEnd />
        </div>
      )}

      {showPage === '问答' && isVisibleRecommendPopup && (
        <div className="assistant-popup" >
          <div className="recommend-box">
            <div className="recommend">
              <div className="list">
                <div className="desc">
                  <div className="robot">
                    <div className="dailyrecommendations">
                      {state.checkedLang
                        ? language.messageEN.bot_question[bot_index].desc
                        : language.messageZH.bot_question[bot_index].desc}
                    </div>

                  </div>
                  <div className="right">
                    <div className="close" onClick={() => toggleVisibility(1)}>
                      <img src={recommendCloseIcon} alt="关闭" />
                    </div>
                  </div>
                </div>

                {state.list.length > 0 ? (
                  state.list.map((item, index) => (
                    <div
                      key={index}
                      className="list-item"
                      onClick={() =>
                        isForbidden() ? '' :
                          clickItemQa(
                            state.checkedLang
                              ? item.quizContentEN
                              : item.quizContent,
                            4
                          )
                      }
                    >
                      <div className={`top-${index + 1}`}>{index + 1}</div>
                      <span className="item">
                        {state.checkedLang
                          ? item.quizContentEN
                          : item.quizContent}
                      </span>
                    </div>
                  ))
                ) : (
                  <div className="text" style={{ color: 'rgba(0, 0, 0, 0.8)' }}>
                    {state.checkedLang
                      ? language.messageEN.study
                      : language.messageZH.study}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {showPage === "问答" &&
        <div className={`left-container ${!isVisibleAssistantLeft ? 'hidden' : ''}`}>
          <AssistantLeft
            className="assistant-left"
            isOpen={isPanelOpen}
            togglePanel={togglePanel}
            onItemSelected={handleItemSelected}
          />

        </div>
      }

      <style jsx="true">{`
       .quest-list {
  line-height: 36px;
  font-size: 14px;
}


.home-card{
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 20px;
  width:1000px;
  margin: 20px auto;
}
  .card-item{
  border-radius: 16px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px 20px;
  height:117px;
 cursor: pointer;
  }
  .notice-icon{
  position: relative;
    top: 2px;
    margin-right: 10px;
  }
.card-title-container{
    display: flex;
    align-items: center;
}
.card-title{
font-weight:500;
}

     .input-box {
        position: relative;
        position: relative;

        flex: 1;
      }
        .input-box  textarea{ 
          overflow-y: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
             border:none !important;
            height:45px !important;
        }
#textarea-box{
            border:none !important;
            height:45px !important;
            padding:10px;
}
input:focus,
textarea:focus,
.assistant-container .assistant-footer .input-box textarea:focus,
.assistant-container .assistant-footer .option-area .input-box textarea:focus,
.el-textarea__inner:focus,
#textarea-box:focus {
  outline: none !important;       
  box-shadow: none !important;    
  border-color: #e0e0e0 !important;
  
}


.cursor-point {
  cursor: pointer !important;

}
.assistant-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: row;
  position: fixed;

  margin-left: 94px;
  background: #fff;
  z-index: 1;
      overflow: hidden;
  background: #fafafa;
  .assistant-left {
    width: 300px;
    height: 95vh;
  }
 
  /* 过渡效果 */
  .shrink-enter-active,
  .shrink-leave-active {
    transition: width 0.5s ease-in-out, opacity 0.5s ease-in-out;
    overflow: hidden;
    /* 防止内容溢出 */
  }

  /* 元素进入时的初始状态：宽度0，透明度0 */
  .shrink-enter {
    width: 0;
    opacity: 0;
  }

  /* 元素进入时的结束状态：宽度100%，透明度1 */
  .shrink-enter-to {
    width: 14vw;
    opacity: 1;
  }

  /* 元素离开时的初始状态：宽度100%，透明度1 */
  .shrink-leave {
    width: 14vw;
    opacity: 1;
  }

  /* 元素离开时的结束状态：宽度0，透明度0 */
  .shrink-leave-to {
    width: 0;
    opacity: 0;
  }


    .session-box {
        width: 56.5vw;
        height: 100%;
        margin: 0 auto;
        padding-right: 3px;
        overflow: auto;
      }

   .greet::-webkit-scrollbar {
        display: none;
      }
         .session-box::-webkit-scrollbar {
        display: none;
      }
  .assistant-right {
    width: 80%;
    height: 95vh;
    position: relative;
   overflow: hidden;
 

    .right-head {
      width: 100%;
      margin-top: 23px;
        gap:20px;
      display: flex;
      align-items: center;
      font-size: 14px;
    

justify-content: flex-end;
      .session-type {
        flex: 1;

        span {
          font-size: 16px;
        }
      }

      .changeLange {
      display:flex;
          flex-direction: row;

        //margin-right: 1.6vw;
        >div {
          display: flex;

          >div {
            width: 50%;
          }

          >div>span {
            background: rgba(92, 178, 255, 0.15);
            display: inline-block;
            width: 100%;
            height: 3.5vh;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
          }

        }

      }

      .changeLange:hover {
        cursor: pointer;
      }

   

      .layout-1 {
        width: 9.9494vw;
      }

      .layout-2 {
        width: 7.0791vw;
      }

      div {
        display: inline-block;
      }
    }

  }

  .assistant-popup {
    border-radius: 14px;
    width:300px;
    height: 100%;
    background: #fff;
    padding: 10px;
    padding-right:20px;
    .recommend-box {
      font-size: 16px;
      width: 260px;
      height: calc(100% - 70px);
      margin: 0 auto;
      padding: 2.7vh;
      border-radius: 14px;
      background: #1196DB0D;



      .desc {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .robot {
          color: #999;
          font-size: 12px;
          margin-bottom: 1.1vh;

          .dailyrecommendations {
            color: #333;
            font-size: 17px;
          }

          div:last-child {
            line-height: 26px;
          }
        }

        .right {
          display: flex;
          flex-direction: column;
          margin-bottom: auto;
        }

        .close {
          width: 16px;
          height: 16px;
          margin: 3px 0 4px;
          margin-left: auto;

          img {
            width: 100%;
            height: 100%;
            font-size: 16px;
          }
        }

        .close:hover {
          cursor: pointer;
        }

        .refresh {
          color: #5cb2ff;
          font-size: 14px;
          display: flex;
          align-items: center;
          gap: 5px;

          span {
            font-size: 16px;
          }
        }

        .refresh:hover {
          cursor: pointer;
        }
      }

      .nav-tab {
        width: 100%;
        height: 2.5vh;
        display: flex;
        margin-bottom: 1.2vh;

        .nav-item {
          width: 25%;
          height: 100%;
          line-height: 2.5vh;
          text-align: center;
          color: #666;
          display: inline-block;

          .item-text {
            line-height: 2.5vh;
            text-align: center;
            font-size: 12px;
          }

          &.active {
            color: #5cb2ff;
            border-bottom: #5cb2ff 1px solid;
          }
        }
      }

      .nav-tab:hover {
        cursor: pointer;
      }

      .list-item {
        display: flex;
        align-items: center;

        div {
          min-width: 2vh;
          min-height: 2vh;
          line-height: 2vh;
          border-radius: 4px;
          font-size: 15px;
          display: inline-block;
          text-align: center;
          margin-right: 6px;
          color: #999;
        }

        .top-1 {
          background: #ea341c;
          color: #fff;
        }

        .top-2 {
          background: #f76f23;
          color: #fff;
        }

        .top-3 {
          background: #f7bb23;
          color: #fff;
        }

        .item {
          display: inline-block;
          flex: 1;
          text-align: left;
          font-size: 14px;
          margin: 1vh 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .item:hover {
          cursor: pointer;
        }
      }

      .text {
        font-size: 14px;
        font-weight: 400;
        line-height: 200px;
        text-align: center;
      }
    }
  }

  .ratesure {
    position: absolute;
    bottom: -36px;
    left: 0;
    right: 0;
    margin: auto;
    top: auto;
    width: 10%;
    display: flex;
    justify-content: center;

    img {
      width: 92px;
    }
  }

  .bg {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;
    border-radius: 14px;
    font-size: 14px;
    z-index: 101;
    background: #fff;
    box-shadow: 3px 0px 6px 0px rgba(92, 178, 255, 0.1);
  }

  .weather {
    height: 60px;
    display: flex;
    align-items: center;
    margin-left: 20px;
    font-weight: 600;
  }

  .tip {
    display: block;
    font-size: 28px;
    color: v-bind("themeColor.textColorLightest");
    margin: 20px 0;
    font-weight: 500;
  }

  .content {
    display: flex;
    margin-top: 24px;
    width: 100%;
    flex-direction: column;
    background: v-bind("themeColor.fillWhite");
    border-radius: 24px;

    &.consultation-mode {
      background: none;
      border-radius: 20px;
      overflow-y: scroll;
      margin: 0 auto;
      z-index: 100;
      width: calc(100% - 60px);

      &::-webkit-scrollbar {
        display: none;
      }
    }

    .desc {
      display: flex;
      color: v-bind("themeColor.textColor");
    }

    .guess-to-ask {
      &>span {
        color: #666;
        font-family: "PingFang SC";
        font-size: 14px;
        font-weight: 400;
        letter-spacing: 0px;
        margin-top: 14px;
        display: block;
      }

      .ask-list {
        margin-bottom: 10px;

        .list-text {
          width: fit-content;
          color: #333;
          font-family: "PingFang SC";
          font-size: 12px;
          font-style: normal;
          font-weight: 400;
          border-radius: 14px;
          border: 1px solid #e6edf4;
          background: #fff;
          margin-top: 10px;
          padding: 10px 12px 10px 20px;
          letter-spacing: 0px;
          line-height: 34px;
          display: flex;
          flex-direction: row;
          align-content: center;

          img {
            width: 8px;
            height: 12px;
            margin-left: 30px;
          }
        }
      }
    }


    .consultation-container {
      margin: 2vh 0;
      display: flex;
      flex-direction: column;

    
      .greet {

        padding-top: 77px;
        overflow: scroll;

        .logo {
          margin-right: 20px;

          img {
            margin-top: 5px;
          }
        }

        .ai-icon {
          width: 56.5vw;
          display: flex;
          margin: 0 auto;
          justify-content: center;
          font-size: 20px;
          color: #333;
          font-family: "PingFang SC";
          font-style: normal;
          font-weight: 400;
          line-height: normal;

          .con {
            position: relative;
         

            .userName {
              color: #5CB2FF;
            }

            span {
              font-weight: bold;
            }

            .con-text {
              position: absolute;
              color: #999;
              font-size: 14px;
              width: 1050px;
              font-weight: 400;
              top: 34px;
            }
          }
        }

        .avatar {
          width: 231px;
          margin-top: -80px;
        }
      }

      .item.itemb {
        flex-direction: column;
        position: relative;

        .con {
          width: auto;
          border-radius: 14;
       background-color:#fff;
          box-shadow: 0px 0px 4px v-bind("themeColor.fillBlueLight");
        }

        .con.loading-mask {
         width: auto;
    border-radius: 14;
    box-shadow: 0px 0px 0.021rem  rgba(92, 178, 255, .4);
        }

        .load-15 {
          font-size: .15rem;
        }

        .k-loader {
          display: inline-block;
          font-size: 0.15rem;
          margin: 0 0.5em;
          position: relative;
          height: 10px;
          width: 10px;
      
        }

        .k-loader:before,
        .k-loader:after {
          content: "";
          display: block;
          height: 10px;
          position: absolute;
          width: 10px;
        }

        .k-loader:before {
          animation: k-loadingK 1s ease-in-out infinite,
            k-loadingM 0.33s ease-in-out infinite;
          background-color: #5cb2ff;
        }

        .k-loader:after {
          animation: k-loadingL 1s ease-in-out infinite,
            k-loadingN 0.33s ease-in-out infinite;
          background-color: #ffb1b1;
        }

        .k-small {
          font-size: 1em;
        }

        .k-large {
          font-size: 4em;
        }

        .k-circle:before,
        .k-circle:after {
          border-radius: 50%;
        }

        .k-circle-before:before {
          border-radius: 50%;
        }

        .k-circle-after:after {
          border-radius: 50%;
        }

        @keyframes k-loadingK {
          0% {
            left: 0;
            transform: scale(1.1);
          }

          50% {
            left: 100%;
            transform: scale(1);
          }

          100% {
            left: 0;
            transform: scale(1.1);
          }
        }

        @keyframes k-loadingL {
          0% {
            left: 100%;
            transform: scale(1.1);
          }

          50% {
            left: 0;
            transform: scale(1);
          }

          100% {
            left: 100%;
            transform: scale(1.1);
          }
        }

        #loading {
          height: 60px;
          width: 100%;
          z-index: 1;
          margin-top: 0px;
          top: 0px;
        }

        #loading-center {
          position: relative;
        }

        #loading-center-absolute {
          width: auto;
        }

        .object {
          width: 8px;
          height: 30px;
          margin-right: 5px;
          background: linear-gradient(152.42deg, #5cb2ff 17.78%, #ffb1b1 100%);
          -webkit-animation: animate 1s infinite;
          animation: animate 1s infinite;
          float: left;
        }

        .object:last-child {
          margin-right: 0px;
        }

        .object:nth-child(10) {
          -webkit-animation-delay: 0.9s;
          animation-delay: 0.9s;
        }

        .object:nth-child(9) {
          -webkit-animation-delay: 0.8s;
          animation-delay: 0.8s;
        }

        .object:nth-child(8) {
          -webkit-animation-delay: 0.7s;
          animation-delay: 0.7s;
        }

        .object:nth-child(7) {
          -webkit-animation-delay: 0.6s;
          animation-delay: 0.6s;
        }

        .object:nth-child(6) {
          -webkit-animation-delay: 0.5s;
          animation-delay: 0.5s;
        }

        .object:nth-child(5) {
          -webkit-animation-delay: 0.4s;
          animation-delay: 0.4s;
        }

        .object:nth-child(4) {
          -webkit-animation-delay: 0.3s;
          animation-delay: 0.3s;
        }

        .object:nth-child(3) {
          -webkit-animation-delay: 0.2s;
          animation-delay: 0.2s;
        }

        .object:nth-child(2) {
          -webkit-animation-delay: 0.1s;
          animation-delay: 0.1s;
        }

        @-webkit-keyframes animate {
          50% {
            -ms-transform: scaleY(0);
            -webkit-transform: scaleY(0);
            transform: scaleY(0);
          }
        }

        @keyframes animate {
          50% {
            -ms-transform: scaleY(0);
            -webkit-transform: scaleY(0);
            transform: scaleY(0);
          }
        }

        .ai-icon {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          img {
            width: 29px;
            height: auto;
          }

          span {
            font-size: 16px;
            font-weight: 500;
            color: #999;
            line-height: initial;
            margin-left: 9px;
            vertical-align: bottom;
          }
        }

        .avatar {
          margin: 0;
        }
      }

      .item.itema {
        display: flex;
        flex-direction: column;
        justify-content: flex-end;

        .file-qa {
          .uploadImg {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: flex-end;
            margin-bottom: 14px;

            .img {
              width: 205px;
              height: 50px;
              padding: 10px;
              border-radius: 10px;
              position: relative;
              border: 1px solid #e7e7e7;
              background-color: #fff;
              display: flex;
              flex-direction: row;
              gap: 8px;

              .img-thumbnail {
                width: 30px;
                height: 30px;
                border-radius: 5px;
                object-fit: cover;
              }

              .img-info {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                height: 100%;

                .img-name {
                  color: #000;
                  font-family: "PingFang SC";
                  font-size: 12px;
                  font-style: normal;
                  font-weight: 400;
                  max-width: 125px;
                  line-height: normal;
                  white-space: nowrap;
                  /* 禁止换行 */
                  overflow: hidden;
                  /* 隐藏溢出的文本 */
                  text-overflow: ellipsis;
                  /* 添加省略号 */
                }

                .img-size {
                  display: flex;
                  gap: 5px;
                  align-items: center;

                  div {
                    color: #999;
                    font-family: "PingFang SC";
                    font-size: 10px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: normal;
                  }
                }
              }
            }
          }
        }

        .img-qa {
          text-align: right;
          width: 100%;
          overflow: hidden;

          img {
            max-width: 60%;
            /* 限制图片最大宽度为容器宽度 */
            max-height: 400px;
            /* 限制图片最大高度为400px */
            height: auto;
            /* 保持宽高比例 */
            width: auto;
            /* 保持宽高比例 */
            object-fit: contain;
            /* 保证图片自适应容器，且不会变形 */
            border-radius: 14px;
            padding: 14px 20px;
            background-color: rgba(92, 178, 255, 0.30);
          }
        }

        .con {
          border-radius: 14px;
          background: rgba(92, 178, 255, 0.3);
          color: #333;
          margin: 30px 0 20px auto;
          width: fit-content;

          .voice-loader {
            margin: auto;
            width: 155px;
            height: 60px;
            display: flex;
            justify-content: center;
            gap: 1px;
          }

          .voice-loader span {
            display: block;
            background: #fff;
            width: 7px;
            height: 10%;
            border-radius: 14px;
            margin-right: 5px;
            float: left;
            margin-top: 15%;
          }

          .voice-loader {
            &>span:last-child {
              margin-right: 0px;
            }

            &>span:nth-child(1) {
              height: 20%;
            }

            &>span:nth-child(2) {
              height: 40%;
              margin-top: 10%;
            }

            &>span:nth-child(3) {
              height: 60%;
              margin-top: 5%;
            }

            &>span:nth-child(4) {
              height: 80%;
              margin-top: 0;
            }

            &>span:nth-child(5) {
              height: 60%;
              margin-top: 5%;
            }

            &>span:nth-child(6) {
              height: 40%;
              margin-top: 10%;
            }

            &>span:nth-child(7) {
              height: 20%;
              margin-top: 15%;
            }
          }

          .voice-loader-animate {
            &>span:last-child {
              margin-right: 0px;
            }

            &>span:nth-child(1) {
              animation: load 1.5s 1.4s infinite linear;
            }

            &>span:nth-child(2) {
              animation: load 1.5s 1.2s infinite linear;
            }

            &>span:nth-child(3) {
              animation: load 1.5s 1s infinite linear;
            }

            &>span:nth-child(4) {
              animation: load 1.5s 0.8s infinite linear;
            }

            &>span:nth-child(5) {
              animation: load 1.5s 0.6s infinite linear;
            }

            .loader span:nth-child(6) {
              animation: load 2.5s 0.4s infinite linear;
            }

            .loader span:nth-child(7) {
              animation: load 2.5s 0.2s infinite linear;
            }
          }

          @keyframes load {
            0% {
              background: #fff;
              margin-top: 15%;
              height: 10%;
            }

            50% {
              background: #f5f5f5;
              height: 100%;
              margin-top: 0%;
            }

            100% {
              background: #fff;
              height: 10%;
              margin-top: 15%;
            }
          }
        }
      }

      .item {
        display: flex;
        justify-content: flex-end;
        margin-top: 20px;

        &:first-child {
          margin-top: 0;
        }

        .module-type {
          margin-top: 24px;

          span {
            margin-right: 24px;
            font-size: 28px;
            font-weight: 500;
            letter-spacing: 0px;
            line-height: 58px;
            color: rgba(148, 162, 176, 1);
            padding: 16px 50px;
            border-radius: 220px;
            background: rgba(240, 241, 242, 1);
          }

          span.active {
            background: rgba(219, 238, 255, 1);
            color: #5cb2ff;
          }
        }

        .avatar {
          margin-left: 16px;
          width: 51.6px;
          margin-right: 16px;
        }

        &:nth-child(2n) {
          justify-content: flex-end;

          .avatar {
            margin-left: 16px;
          }
        }

        .con {
          max-width: 100%;
          display: flex;
          flex-direction: column;
          padding: 14px 20px;
          border-radius: 24px;
          color: v-bind("themeColor.textColor");
          // box-shadow: 0px 0px 8px v-bind("themeColor.shadowColor");
          // font-size: 28px;
          overflow: hidden;

          .con-text {
            display: flex;
            flex-direction: column;
            // white-space: pre-wrap;
            overflow: hidden;

            ref {
              color: #999;
            }

            li {
              a {
                color: #5cb2ff;
              }
            }

            a {
              color: #5cb2ff !important;
            }

            .docname {
              font-size: 24px;
              color: v-bind("themeColor.textColor");
            }

            span {
              font-size: 28px;
            }

            .think-style {
              color: #999;
            }
          }

          .con-file {
            display: flex;
            flex-direction: column;
            margin-top: 20px;
            gap: 6px;

            .el-collapse-item__header {
              font-size: 10px !important;
              height: 35px !important;
            }

            .activeName {
              color: #333;
              font-family: "PingFang SC";
              font-size: 14px;
              font-style: normal;
              font-weight: 400;
              line-height: normal;
            }

            .fromto {
              color: v-bind("themeColor.textColorLighten");
            }

            .file-item {
              color: #666;
              font-family: "PingFang SC";
              font-size: 14px;
              font-style: normal;
              font-weight: 400;
              line-height: normal;
              margin: 4px 0px;
              word-break: break-all;

              &.active {
                color: #5cb2ff;
              }

              div:last-child {
                margin-top: 20px;
              }

              a {
                text-decoration: underline;
                color: #5cb2ff;
              }

              .iconfont {
                color: #5cb2ff;
                margin-right: 4px;
              }
            }
          }

          // .features {
          //   display: flex;
          //   flex-direction: row;
          //   justify-content: space-between;
          //   align-content: center;
          //   font-size: 14px;
          //   height: 40px;
          // }

          .con-opt {
            display: flex;
            justify-content: space-between;

            .left {
              display: flex;
              align-items: center;

              img {
                width: 14px;
                margin-right: 26px;
              }

              img:hover {
                cursor: pointer;
              }

              span {
                margin-left: 68px;

                &:first-child {
                  margin-left: 0;
                }

                &.icon-good-a-copy,
                &.icon-quxiaodianzan-a-copy {
                  color: #e97600;
                }
              }
            }

            .right {
              img {
                width: 36px;
                margin-left: 45px;
              }
            }
          }
        }
      }
    }
  }

  .rate {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;

    .demo-rate-block {
      margin-left: 15px;
    }

    .rate-submit {

      margin-left: 8px;

      div {
        display: inline-block;
        margin-right: 10px;
        color: #999;
        font-family: "PingFang SC";
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
      }

      &.active {
        div {
          color: #5cb2ff;
        }

        div:hover {
          cursor: pointer;
        }
      }
    }

    &>div {
      color: #666;
      font-family: "PingFang SC";
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
    }
  }

  .cxb-box {
    // position: fixed;
    z-index: 15;

    .cxb {
      img {
        width: 100px;
      }
    }

    .cxb-text {
      position: absolute;
      top: 0;
      left: 80px;

      img {
        width: 136px;
        margin-top: 20px;
      }
    }
  }

  .img-preview {
    background: #ffffff;
    width: 100%;
    padding: 20px 0 30px;


    .uploadImg {
      width: 100%;
      overflow-x: auto;
      display: flex;
      gap: 10px;

      .img {
        width: 205px;
        height: 50px;
        padding: 10px;
        border-radius: 10px;
        flex-shrink: 0;
        /* 防止子元素收缩 */
        position: relative;
        border: 1px solid #e7e7e7;
        display: flex;
        flex-direction: row;
        gap: 8px;

        .img-thumbnail {
          width: 30px;
          height: 30px;
          border-radius: 5px;
          object-fit: cover;
        }

        .img-info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 100%;

          .img-name {
            color: #000;
            font-family: "PingFang SC";
            font-size: 11px;
            font-style: normal;
            font-weight: 400;
            max-width: 125px;
            line-height: normal;
            white-space: nowrap;
            /* 禁止换行 */
            overflow: hidden;
            /* 隐藏溢出的文本 */
            text-overflow: ellipsis;
            /* 添加省略号 */
          }

          .img-size {
            display: flex;
            gap: 5px;
            align-items: center;

            div {
              color: #999;
              font-family: "PingFang SC";
              font-size: 10px;
              font-style: normal;
              font-weight: 400;
              line-height: normal;
            }
          }
        }

        .closeImg {
          font-size: 0px;
          top: 6px;
          right: 8px;
          position: absolute;

          img {
            width: 14px;
            height: 14px;
            object-fit: contain;
          }

          img:hover {
            cursor: pointer;
          }
        }
      }
    }
  }

  .assistant-footer {
    width: 1000px;
    display: flex;
    flex-direction: column;
    // left: 26vw;
 margin: 0 auto;
     border-bottom: 2px solid #2ea3df;
    padding: 10px 30px;
    background: #ffffff;
    box-shadow: 0px 4px 12px rgba(92, 178, 255, 0.2);
    z-index: 100;
    border-radius: 14px;
    position: relative;
    // 上传图片缩略图

    .fileUpload {
      position: absolute;
      width: 346px;
      height: 90px;
      display: flex;
      top: -90px;
      left: 0;
      z-index: 200;

      .select {
        width: 116px;
        height: 82px;
        border-radius: 10px;
        background: #fff;
        box-shadow: 0px 4px 12px 0px rgba(92, 178, 255, 0.2);
        padding: 17px;
        color: #333;
        font-size: 14px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-top: 8px;

        div {
          display: flex;
          align-items: center;

          img {
            width: 16px;
            height: 16px;
            margin-right: 7px;
          }
        }

        div:hover {
          cursor: pointer;
        }
      }

      .tips {
        width: 226px;
        height: 69px;
        margin-bottom: 20px;
        position: relative;

        img {
          width: 226px;
          height: 69px;
        }

        p {
          position: absolute;
          top: 10px;
          right: 10px;
          color: #fff;
          font-family: "PingFang SC";
          font-size: 12px;
          width: 198px;
          height: 49px;
        }
      }
    }

    .recommendIcon {
      position: absolute;
      width: 86px;
      height: 28px;
      top: -100px;
      right: 0;

      div {
        position: relative;
      }

      img {
        position: absolute;
        top: -32px;
        left: 11px;
        width: 29px;
        height: 35px;
      }

      span {
        display: block;
        width: 100%;
        height: 28px;
        border-radius: 15px;
        background: #5cb2ff;
        color: #fff;
        font-size: 14px;
        line-height: 28px;
        text-align: center;
      }

      span:hover {
        cursor: pointer;
      }
    }

    .option-area {
      display: flex;
      font-size: 18px;

      .other-opt {
        align-self: center;
        display: flex;
        width: 20px;
        margin-top: 15px;
      }

      .other-opt:hover {
        cursor: pointer;
      }


      .other-yuyin {
        display: flex;
        width: 50px;
        margin-left: 20px;

        &.type2:hover {
          cursor: pointer;
        }
      }
    }

    .area-con {
      display: flex;
      width: 100%;
      padding: 20px 0;
      border-top: 1px solid #f5f5f5;

      .van-row {
        width: 100%;
        justify-content: center;
      }

      .area-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: v-bind("themeColor.textColorLighten");
        font-size: 24px;

        img {
          width: 86px;
          margin-bottom: 10px;
          border: 1px dashed v-bind("themeColor.borderColorLighten");
        }
      }
    }

    .ver {
      position: absolute;
      bottom: 103%;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      font-size: 20px;
      color: #4c4c4c;
      opacity: 0.5;
    }
  }

  .warn {
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
    position: absolute;
    text-align: center;
    margin-top: 36px;
    color: #999;
    font-family: "PingFang SC";
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }
}

.feedback-box {
  .title {
    font-size: 16px;
  }

  .sub {
    width: 94%;
    display: flex;
    flex-direction: row-reverse;
    margin: 10px 30px 0;
  }
}



        .loading-mask {
            width: 40px;
            height: 40px; 
            position: relative;
        }

        /* 小球样式 */
        .ball {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            left: 30px;
            transform-origin: 10px; /* 设置小球旋转半径 */
            animation: rotate 1s linear infinite; /* 小球旋转动画 */
        }

        .ball:nth-child(1) {
            background-color: #5cb2ff; /* 蓝色 */
            animation-delay: 0s;
        }

        .ball:nth-child(2) {
            background-color: #ffb1b1; /* 粉红色 */
            animation-delay: -0.5s;
        }

        /* 定义关键帧 */
        @keyframes rotate {
       0% {
                transform: translateX(-10px) translateY(-50%); /* 左边起点 */
            }
            50% {
                transform: translateX(10px) translateY(-50%); /* 右边终点 */
            }
            100% {
                transform: translateX(-10px) translateY(-50%); /* 回到左边起点 */
            }
        }



.left-container {
  width: 300px; /* Full width when visible */
  height: 95vh;
  transition: transform 0.5s cubic-bezier(0.4, 0.0, 0.2, 1), width 0.5s cubic-bezier(0.4, 0.0, 0.2, 1); /* Smoother, more gradual transition */
  overflow: hidden;
  will-change: transform, width; /* Performance optimization for animations */
}


.left-container.hidden {
  transform: translateX(-100%);
  width: 0;

}


.changeLange {
  display: flex;

  border: 1px solid #ccc;
  padding: 5px;
  border-radius: 4px;
}

.language-option {
  cursor: pointer;
  margin: 0 5px;
}

.separator {
  margin: 0 5px;
}

.active-lang {
  color: #259edd; /* 选中的文字变蓝 */
}
  .new-chart{
  display: flex !important;
 gap:6px;
    font-weight: 500;
    border: 1px solid #ccc;
    padding: 5px 10px;
    border-radius: 4px;
      cursor:pointer;
  
  }
    .cursor-pointer{
    cursor:pointer;
    }

        .left-container {
          width: 400px;
          height: 95vh;
          position: absolute;
          right: 0;  /* Changed from left: 0 to right: 0 */
          top: 0;
          border-left:2px solid #f5f5f5;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          transform: translateX(0);
          opacity: 1;
          visibility: visible;
        margin:20px 0;
          z-index: 100;
        }

        .left-container.hidden {
          transform: translateX(100%); /* Changed from -100% to 100% */
          opacity: 0;
          visibility: hidden;
        }

        .cursor-pointer {
          cursor: pointer;
          transition: transform 0.3s ease;
        }

        .cursor-pointer.active {
          transform: rotate(180deg);
        }

        .assistant-right {
          position: relative;
          transition: margin-right 0.3s cubic-bezier(0.4, 0, 0.2, 1); /* Changed from margin-left */
          margin-right: ${isVisibleAssistantLeft ? '300px' : '0'}; /* Changed from margin-left */
          width: auto; /* Added to ensure proper content width */
        }
          .send-container{
          display:flex;
        gap:10px;
            align-items: center;
         cursor: pointer;
          }
        .send-container img{
          
          widht:25px;height:25px}
      `}</style>
    </div>
  );
}

export default AssistantContainer;